package com.neustudy.content.service.impl;

import com.neustudy.content.mapper.CourseCategoryMapper;
import com.neustudy.content.model.dto.CourseCategoryTreeDto;
import com.neustudy.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author WKX
 * @version 1.0
 * @describe todo
 * @create: 2024-11-06 18:06
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {

        List<CourseCategoryTreeDto> CourseCategorylist = new ArrayList<>();
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        Map<String , CourseCategoryTreeDto> CourseCategorymap = courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).collect(Collectors.toMap(k ->k.getId() , v->v , (k1, k2)->k1 ));
        courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).forEach(item->{
            if(item.getParentid().equals(id)){
                CourseCategorylist.add(item);
            }
            CourseCategoryTreeDto parent = CourseCategorymap.get(item.getParentid());
            if(parent != null){
                if(parent.getChildrenTreeNodes() == null){
                    parent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                parent.getChildrenTreeNodes().add(item);
            }
        });
        return CourseCategorylist;
    }
}
